package com.travel.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.travel.entities.Train;
import com.travel.util.Constants;
import com.travel.util.HttpClientUtil;

/**
 * 火车及火车票服务
 *
 * @author SAGITTAR
 */
public class TrainService {

	private static final Logger LOGGER = LogManager.getLogger(TrainService.class);

    /**
     * 站到站查询，包含票价
     *
     * @param startStation 起点站，非空
     * @param endStation 终点站，非空
     * @param startDate 出发日期，可空
     * @return 列车信息
     */
	public List<Train> getTrainListByStation(String startStation, String endStation, String startDate) {
		Map<String, String> params = new HashMap<>(8);
		params.put("start", startStation);
		params.put("end", endStation);
		if (StringUtils.isNotBlank(startDate)) {
			params.put("date", startDate);
		}
		JSONObject resultJson = get(params, "s2swithprice");
		LOGGER.debug("查询结果为{}", resultJson);
		List<Train> trainList = new ArrayList<>();
		JSONArray listArray = resultJson.optJSONArray("list");
		for (int index = 0; Objects.nonNull(listArray) && index < listArray.length(); index++) {
			JSONObject trainJson = listArray.optJSONObject(index);
			LOGGER.info("查询列车信息为{}", trainJson);
			// 列车信息
			Train train = new Train();
			train.setNumber(trainJson.optString("train_no"));
			train.setType(trainJson.optString("train_type"));
			train.setStartStation(trainJson.optString("start_station"));
			train.setStartStationType(trainJson.optString("start_station_type"));
			train.setEndStation(trainJson.optString("end_station"));
			train.setEndStationType(trainJson.optString("end_station_type"));
			train.setStartTime(trainJson.optString("start_time"));
			train.setEndTime(trainJson.optString("end_time"));
			train.setRunTime(trainJson.optString("run_time"));
            train.setRunDistance(" -- ");
			// 车票信息
			Train.TrainPrice trainPrice = train.new TrainPrice();
			JSONArray priceArray = trainJson.optJSONArray("price_list");
			for (int priceIndex = 0; priceIndex < priceArray.length(); priceIndex++) {
				JSONObject priceJson = priceArray.optJSONObject(priceIndex);
				if (priceJson.optString("price_type").contentEquals("商务座")) {
					trainPrice.setBusiness(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("特等座")) {
					trainPrice.setSpecial(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("一等座")) {
					trainPrice.setFirstClass(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("二等座")) {
					trainPrice.setSecondClass(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("高级软卧")) {
					trainPrice.setHighSoftSleep(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("软卧")) {
					trainPrice.setSoftSleep(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("硬卧")) {
					trainPrice.setHardSleep(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("软座")) {
					trainPrice.setSoftSeat(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("硬座")) {
					trainPrice.setHardSeat(priceJson.optString("price"));
				} else if (priceJson.optString("price_type").contentEquals("无座")) {
					trainPrice.setStanding(priceJson.optString("price"));
				}
			}
			train.setTrainPrice(trainPrice);
			LOGGER.info("解析列车信息为{}", new JSONObject(train));
			trainList.add(train);
		}
		return trainList;
	}

	 /**
     * 官方接口。站到站查询，包含票价
     * https://kyfw.12306.cn/otn/leftTicketPrice/query?
     * leftTicketDTO.train_date=2019-06-14
     * &leftTicketDTO.from_station=ESN
     * &leftTicketDTO.to_station=CSQ
     *
     * @param startStation 起点站，非空
     * @param endStation 终点站，非空
     * @param startDate 出发日期，可空
     * @return 列车信息
     */
    public List<Train> getTrainListByStation12306(String startStation, String endStation, String startDate) {
        Map<String, String> params = new HashMap<>(8);
        params.put("leftTicketDTO.from_station", startStation);
        params.put("leftTicketDTO.to_station", endStation);
        if (StringUtils.isNotBlank(startDate)) {
            params.put("leftTicketDTO.train_date", startDate);
        }
        JSONArray listArray = get12306(params);
        LOGGER.debug("查询结果为{}", listArray);
        List<Train> trainList = new ArrayList<>();
        // JSONArray listArray = resultJson.optJSONArray("list");
        for (int index = 0; Objects.nonNull(listArray) && index < listArray.length(); index++) {
            JSONObject trainJson = listArray.optJSONObject(index).optJSONObject("queryLeftNewDTO");

            LOGGER.info("查询列车信息为{}", trainJson);
            // 列车信息
            Train train = new Train();
            train.setNumber(trainJson.optString("station_train_code"));
            train.setType(" -- ");
            train.setStartStation(trainJson.optString("from_station_name"));
            train.setStartStationType(" -- ");
            train.setEndStation(trainJson.optString("to_station_name"));
            train.setEndStationType(" -- ");
            train.setStartTime(trainJson.optString("start_time"));
            train.setEndTime(trainJson.optString("arrive_time"));
            train.setRunTime(trainJson.optString("lishi"));
            train.setRunDistance(" -- ");
            // 车票信息
            Train.TrainPrice trainPrice = train.new TrainPrice();
            String swz_price = "--";
            String tz_price = "--";
            String zy_price = "--";
            String ze_price = "--";
            String hbrw_price = "--";
            String rw_price = "--";
            String yw_price = "--";
            String rz_price = "--";
            String yz_price = "--";
            String wz_price = "--";
            if (!trainJson.optString("swz_price").equals("--")) {
                swz_price = String.valueOf(Double.valueOf(trainJson.optString("swz_price")) / 10);
            }
            if (!trainJson.optString("tz_price").equals("--")) {
                tz_price = String.valueOf(Double.valueOf(trainJson.optString("tz_price")) / 10);
            }
            if (!trainJson.optString("zy_price").equals("--")) {
                zy_price = String.valueOf(Double.valueOf(trainJson.optString("zy_price")) / 10);
            }
            if (!trainJson.optString("ze_price").equals("--")) {
                ze_price = String.valueOf(Double.valueOf(trainJson.optString("ze_price")) / 10);
            }
            if (!trainJson.optString("hbrw_price").equals("--")) {
                hbrw_price = String.valueOf(Double.valueOf(trainJson.optString("hbrw_price")) / 10);
            }
            if (!trainJson.optString("rw_price").equals("--")) {
                rw_price = String.valueOf(Double.valueOf(trainJson.optString("rw_price")) / 10);
            }
            if (!trainJson.optString("yw_price").equals("--")) {
                yw_price = String.valueOf(Double.valueOf(trainJson.optString("yw_price")) / 10);
            }
            if (!trainJson.optString("rz_price").equals("--")) {
                rz_price = String.valueOf(Double.valueOf(trainJson.optString("rz_price")) / 10);
            }
            if (!trainJson.optString("yz_price").equals("--")) {
                yz_price = String.valueOf(Double.valueOf(trainJson.optString("yz_price")) / 10);
            }
            if (!trainJson.optString("wz_price").equals("--")) {
                wz_price = String.valueOf(Double.valueOf(trainJson.optString("wz_price")) / 10);
            }
            trainPrice.setBusiness(swz_price);
            trainPrice.setSpecial(tz_price);
            trainPrice.setFirstClass(zy_price);
            trainPrice.setSecondClass(ze_price);
            trainPrice.setHighSoftSleep(hbrw_price);
            trainPrice.setSoftSleep(rw_price);
            trainPrice.setHardSleep(yw_price);
            trainPrice.setSoftSeat(rz_price);
            trainPrice.setHardSeat(yz_price);
            trainPrice.setStanding(wz_price);
            train.setTrainPrice(trainPrice);
            LOGGER.info("解析列车信息为{}", new JSONObject(train));
            trainList.add(train);
        }
        return trainList;
    }
    
    /**
     * 请求官方数据
     *
     * @param params 请求参数
     * @param url 补充URL
     * @return 接口返回值
     */
    private static JSONArray get12306(Map<String, String> params) {
        String baseUrl = "https://kyfw.12306.cn/otn/leftTicketPrice/query?";
        // 拼接请求参数
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        for (Map.Entry<String, String> nameValuePairs : params.entrySet()) {
            String encodedValue = null;
            try {
                encodedValue = URLEncoder.encode(nameValuePairs.getValue(), Constants.UTF_8);
            } catch (UnsupportedEncodingException e) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }
            urlBuilder.append(String.format("&%s=%s", nameValuePairs.getKey(), encodedValue));
        }
        System.out.println(urlBuilder.toString());
        JSONArray resultJson = null;
        try {
            // 解析返回值，返回result
            JSONObject retJson = new JSONObject(HttpClientUtil.getWebPage(urlBuilder.toString()));
            if (retJson.optInt("httpstatus") == 200) {
                resultJson = retJson.optJSONArray("data");
            } else {
                LOGGER.error(retJson.optString("reason"));
            }
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
        if (Objects.isNull(resultJson)) {
            resultJson = new JSONArray();
        }
        LOGGER.info("{}的接口返回值为{}", resultJson);
        return resultJson;
    }
    
	/**
	 * GET请求
	 *
	 * @param params 请求参数
	 * @param url 补充URL
	 * @return 接口返回值
	 */
	private static JSONObject get(Map<String, String> params, String url) {
		String baseUrl = "http://apis.juhe.cn/train/%s?";
		// 拼接请求参数
		StringBuilder urlBuilder = new StringBuilder(String.format(baseUrl, url));
		urlBuilder.append("key=dc2f9c2d512a422704e36c1bccbd97e2");
		if (!params.containsKey("dtype")) {
			params.put("dtype", "json");
		}
		for (Map.Entry<String, String> nameValuePairs : params.entrySet()) {
			String encodedValue = null;
			try {
				encodedValue = URLEncoder.encode(nameValuePairs.getValue(), Constants.UTF_8);
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(e.getLocalizedMessage(), e);
			}
			urlBuilder.append(String.format("&%s=%s", nameValuePairs.getKey(), encodedValue));
		}
		JSONObject resultJson = null;
		try {
			// 解析返回值，返回result
			JSONObject retJson = new JSONObject(HttpClientUtil.getWebPage(urlBuilder.toString()));
			if (retJson.optInt("error_code") == 0) {
				resultJson = retJson.optJSONObject("result");
			} else {
				LOGGER.error(retJson.optString("reason"));
			}
		} catch (IOException e) {
			LOGGER.error(e.getLocalizedMessage(), e);
		}
		if (Objects.isNull(resultJson)) {
			resultJson = new JSONObject();
		}
		LOGGER.info("{}的接口返回值为{}", url, resultJson);
		return resultJson;
	}
}
